package com.hoshiicloud.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.goods.entity.goods.Gallery;
import com.hoshiicloud.goods.entity.goods.GoodsGallery;
import com.hoshiicloud.goods.entity.sku.BaseSku;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.entity.sku.ProductManage;
import com.hoshiicloud.goods.entity.sku.VendorGoodsSku;
import com.hoshiicloud.goods.entity.spu.*;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.feign.StoreFeignService;
import com.hoshiicloud.goods.mapper.spu.ExtSpuMapper;
import com.hoshiicloud.goods.service.*;
import com.hoshiicloud.goods.vo.ExtSpuDisplayVo;
import com.hoshiicloud.user.entity.store.PlatStore;
import com.hoshiicloud.user.param.PlatStoreQueryParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 扩展SPU 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class ExtSpuServiceImpl extends ServiceImpl<ExtSpuMapper, ExtSpu> implements ExtSpuService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private ExtSpuMapper extSpuMapper;
    @Autowired
    private ExtSkuService extSkuService;
    @Autowired
    private GoodsCategoryService goodsCategoryService;
    @Autowired
    private BaseSpuService baseSpuService;
    @Autowired
    private BaseSkuService baseSkuService;

    @Autowired
    private StoreFeignService storeFeignService;
    @Autowired
    private ProductManageService productManageService;
    @Autowired
    private SpuSalesCategoryService spuSalesCategoryService;
    @Autowired
    private ExtSpuTagsService extSpuTagsService;
    @Autowired
    private GoodsGalleryService goodsGalleryService;
    @Autowired
    private GalleryService galleryService;
    @Autowired
    private VendorGoodsSkuService vendorGoodsSkuService;
    @Autowired
    private BaseGoodsGalleryService baseGoodsGalleryService;

    /**
     * @param id
     * @return ExtSpu
     * @description: 根据id查询扩展SPU
     */
    @Override
    @Cacheable(cacheNames = "ExtSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-扩展SPU-查询扩展SPU ")
    public ExtSpu getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增扩展SPU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    @Logable(authName = "商品管理-扩展SPU-新增扩展SPU")
    public boolean save(ExtSpu entity) {

        // 生成主键ID
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改扩展SPU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    @Logable(authName = "商品管理-扩展SPU管理-修改扩展SPU")
    public boolean updateById(ExtSpu entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param queryWrapper 查询条件
     * @return IPage
     * @description: 分页查询扩展SPU
     */
    @Override
    @Logable(authName = "商品管理-扩展SPU管理-分页查询扩展SPU")
    @Cacheable(cacheNames = "ExtSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public IPage getPage(IPage page, Wrapper queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    @Logable(authName = "商品管理-扩展SPU管理-删除扩展SPU")
    public boolean deleteById(Long id) {
        // 根据id查询数据
        ExtSpu entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException("删除扩展SPU异常，无法找到扩展SPU记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "ExtSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-扩展SPU管理-根据id集合查询扩展SPU")
    public List<ExtSpu> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 保存分店ExtSpu
     */
    @Override
    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    public ExtSpu saveExtSpu(ExtSpu entity) {

        // 生成主键ID
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return entity;
    }

    /**
     * 获取SPU信息加上最低售价（最低售价从sku表获取，如果一个spu对应多个sku，获取最低售价）
     *
     * @return Page<Map < String, Object>>
     */
    @Override
    @Logable(authName = "商品管理-扩展SPU管理-获取SPU信息加上最低售价")
    @Cacheable(cacheNames = "ExtSpu", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5(#root.targetClass.simpleName+':'+#root.methodName+':'+#key)")
    public IPage getSpusWithMiniPrice(Page page, Wrapper queryWrapper, String key) {
        return extSpuMapper.getSpusWithMiniPrice(page, queryWrapper);
    }

    /**
     * 获取SPU商品详情加上类目和标签信息以及最低价（最低售价从sku表获取，如果一个spu对应多个sku，获取最低售价。 类目从spu_sales_category表获取关联goods_category表，标签从ext_spu_tags表获取）
     *
     * @return Map<String, Object>
     */
    @Cacheable(cacheNames = "ExtSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-扩展SPU管理-获取SPU商品详情加上类目和标签信息以及最低价")
    @Override
    public List<Map<String, Object>> getSpuDetailWithOthers(String key) {
        // try {
        log.info("查询扩展SPU详情带售价标签类目");
        QueryWrapper<ExtSpu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != key, "t.id", key);
        try {
            queryWrapper.select(BeanUtils.getSqlSelect(ExtSpu.class));
        } catch (Exception e) {
            throw new ServiceException("...");
        }
        return extSpuMapper.getSpuDetailWithOthers(queryWrapper);
        // } catch (Exception e) {
        //     log.error("查询扩展SPU详情带售价标签类目异常", e);
        //     throw new ServiceException("查询扩展SPU详情带售价标签类目异常");
        // }
    }

    /**
     * 分页查询商品列表
     */
    @Override
    public Page listExtSpuDisplays(Map<String, Object> map) {
        Page page = new Page(Long.valueOf(map.get("pageNumber").toString()),Long.valueOf(map.get("pageSize").toString()));

        String orderField = map.getOrDefault("orderField","createdTime").toString();
        String orderType = map.getOrDefault("orderType","DESC").toString();
        if(StringUtils.isBlank(orderField)){
            orderField = "createdTime";
        }
        if(StringUtils.isBlank(orderType)){
            orderType = "DESC";
        }
        map.put("orderByCondition","ORDER BY " + orderField +" " + orderType);

        List<ExtSpuDisplayVo> extSpuDisplayVos = extSpuMapper.listExtSpuDisplays(page, map);
        this.imageHandle(extSpuDisplayVos);
        extSpuDisplayVos.stream().forEach(s -> {
            s.setCategoryName(goodsCategoryService.getById(s.getCategoryId()).getName());
        });
        page.setRecords(extSpuDisplayVos);
        return page;
    }

    /**
     * ExtSpu 商品上下架
     */
    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    @Transactional
    @Override
    public Boolean extSpuShelvesUpAndDown(Long extId, Map<String, Long> userMessage, Integer status) {

        // 获取：店铺id+总店id 的集合
        long parentId = Long.parseLong(userMessage.get("storeId").toString());
        List<Long> storeIds = this.storeIds(parentId);

        // 根据id查询ExtSpu
        ExtSpu extSpu = this.getById(extId);
        Long baseSpuId = extSpu.getSpuId();

        // 上下架 BaseSpu
        BaseSpu baseSpu = new BaseSpu();
        baseSpu.setId(baseSpuId);
        baseSpu.setStatus(status);
        baseSpu.setDeleted(0);
        baseSpuService.updateById(baseSpu);

        // 上下架 ExtSpu （总店+分店）
        QueryWrapper<ExtSpu> extSpuWrapper = new QueryWrapper<>();
        extSpuWrapper.lambda().eq(ExtSpu::getSpuId, baseSpuId).in(ExtSpu::getStoreId, storeIds).eq(ExtSpu::getDeleted,0);
        ExtSpu extSpuUpdate = new ExtSpu();
        extSpuUpdate.setStatus(status);
        extSpuUpdate.setDeleted(0);
        if (status == 1) {
            extSpuUpdate.setUpTime(LocalDateTime.now());
        }else {
            extSpuUpdate.setDownTime(LocalDateTime.now());
        }

        UpdateBatchParam<ExtSpu> extSpuBatch = new UpdateBatchParam();
        extSpuBatch.setWrapper(extSpuWrapper);
        extSpuBatch.setUpdateEntity(extSpuUpdate);
        this.updateBatchByWrapper(extSpuBatch);


        // 上下架BaseSku
        QueryWrapper<BaseSku> baseSkuWrapper = new QueryWrapper<>();
        baseSkuWrapper.lambda().eq(BaseSku::getSpuId, baseSpuId).eq(BaseSku::getDeleted, 0);

        // 根据 查询条件查询 baseSku
        BaseSku baseSku = baseSkuService.getOne(baseSkuWrapper);

        // 对BaseSku进行上下架
        BaseSku baseSkuUpdate = new BaseSku();
        baseSkuUpdate.setStatus(status);
        baseSkuUpdate.setDeleted(0);

        UpdateBatchParam<BaseSku> baseSkuBatch = new UpdateBatchParam<>();
        baseSkuBatch.setWrapper(baseSkuWrapper);
        baseSkuBatch.setUpdateEntity(baseSkuUpdate);
        baseSkuService.updateBatchByWrapper(baseSkuBatch);

        // 上下架 ExtSku (总店+分店)
        List<OmnipotentWrapper> extSkuOmiList = new ArrayList<>();
        extSkuOmiList.add(OmnipotentWrapper.setWrapper("eq", "sku_id", baseSku.getId()));
        extSkuOmiList.add(OmnipotentWrapper.setWrapper("in", "store_id", storeIds));
        extSkuOmiList.add(OmnipotentWrapper.setWrapper("eq", "deleted", 0));

        ExtSku extSkuUpdate = new ExtSku();
        extSkuUpdate.setDeleted(0);
        if (status == 1) {
            extSkuUpdate.setStatus(2);
        }else {
            extSkuUpdate.setStatus(3);
        }

        OmnipotentParam<ExtSku> extSkuParam = new OmnipotentParam<>();
        extSkuParam.setWrappers(extSkuOmiList);
        extSkuParam.setEntity(extSkuUpdate);

        extSkuService.omniExtSkuUpdate(extSkuParam);

        return true;
    }

    /**
     * 根据店铺和经营类目获取SPU信息加上最低售价（最低售价从sku表获取，如果一个spu对应多个sku，获取最低售价）
     *
     * @param page 分页对象
     * @param entityWrapper 查询参数
     * @return Page<Map < String, Object>>
     */
    @Cacheable(cacheNames = "ExtSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-扩展SPU管理-获取SPU信息加上最低售价")
    @Override
    public Page<Map<String, Object>> getSpusByStoreIdAndCategoryId(Page page, Wrapper<ExtSpu> entityWrapper,
            String key) {
        return extSpuMapper.getSpusByStoreIdAndCategoryId(page, entityWrapper);
    }

    /**
     * 批量删除
     */
    @Override
    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    @Transactional
    public Boolean delectByIds(List<Long> ids, Map<String, Object> map) {

        //  根据总店Id查询所有分点
        long storeId = Long.parseLong(map.get("storeId").toString());
        PlatStoreQueryParam storeQueryParam = new PlatStoreQueryParam();
        storeQueryParam.setPageNumber("1");
        storeQueryParam.setPageSize("10000");
        storeQueryParam.setParentId(storeId);
        storeQueryParam.setDeleted(0);
        List<PlatStore> records = storeFeignService.getPlatStorePage(storeQueryParam).getData().getRecords();
        List<Long> storeIds = records.stream().map(PlatStore::getId).collect(Collectors.toList());

        // 更具ExtSpuId 查询ExtSpu信息
        List<ExtSpu> extSpus = baseMapper.selectBatchIds(ids);

        // 删除baseSpu
        Set<Long> baseSpuIds = extSpus.stream().map(ExtSpu::getSpuId).collect(Collectors.toSet());
        QueryWrapper<BaseSpu> baseSpuWrapper = new QueryWrapper<>();
        baseSpuWrapper.lambda().in(BaseSpu::getId, baseSpuIds).eq(BaseSpu::getDeleted, 0);
        BaseSpu baseSpuUpdate = new BaseSpu();
        baseSpuUpdate.setDeleted(1);
        baseSpuUpdate.setStatus(2);

        UpdateBatchParam<BaseSpu> updateBatchParam = new UpdateBatchParam();
        updateBatchParam.setWrapper(baseSpuWrapper);
        updateBatchParam.setUpdateEntity(baseSpuUpdate);
        baseSpuService.updateBatchByWrapper(updateBatchParam);

        // 批量删除 baseGoodsGallery
        this.deletedBaseGoodsGallery(baseSpuIds);

        // 删除ExtSpu
        this.delExtSpu(storeIds, baseSpuIds,extSpus);

        // 删除 VendorGoodsSku
        this.deletedVendorGoodsSku(baseSpuIds);

        // 删除spu下的sku
       this.delSkuUnderSpuById(storeIds, baseSpuIds, map);
        return true;
    }

    @Override
    @Cacheable(cacheNames = "ExtSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#storeId")
    @Logable(authName = "商品管理-扩展商品SpU管理-根据storeId 获取ext_spu")
    public List<ExtSpu> listByStoreId(Long storeId) {
        QueryWrapper<ExtSpu> q = new QueryWrapper<>();
        q.lambda().eq(ExtSpu::getStoreId, storeId).eq(ExtSpu::getDeleted, 0);
        return baseMapper.selectList(q);
    }

    @Override
    @Cacheable(cacheNames = "ExtSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-扩展商品SpU管理-根据店铺id集合 获取base_spu_id串 ")
    public Map<String, String> queryStoresAndBaseSpuIds(List<Long> storeIds, String key) {
        QueryWrapper<ExtSpu> q = new QueryWrapper<>();
        q.lambda().in(ExtSpu::getStoreId, storeIds).eq(ExtSpu::getDeleted, 0)
                .groupBy(ExtSpu::getStoreId);
        q.select("store_id as storeId,group_concat(spu_id) as title");
        List<ExtSpu> list = this.list(q);
        Map<String, String> map = new HashMap<>();
        if(list.size() >0){
            for (ExtSpu s : list) {
                map.put(s.getStoreId().toString(), StringUtils.isNotBlank(s.getTitle()) ? s.getTitle() : "无");
            }
        }else{
            for(Long s:storeIds){
                map.put(s.toString(),"无");
            }
        }
        return map;
    }

    @Override
    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    @Logable(authName = "商品管理-扩展商品SpU管理-批量保存扩展spu ")
    public Boolean saveBatch1(List<ExtSpu> list) {
        return this.saveBatch(list);
    }

    /**
     * 删除扩展spu
     */
    private void delExtSpu(List<Long> storeIds,  Set<Long> baseSpuIds, List<ExtSpu> extSpus) {

        // 存储需要删除的 ExtSpu的Id, 用于删除以ExtSpu的id为外键的相关联的表的数据
        List<Long> allExtSpuId = new ArrayList<>();
        // 添加总店的 ExtSpu的id
        extSpus.forEach(s -> allExtSpuId.add(s.getId()));

        //  删除总店的ExtSpu
        extSpus.stream().forEach(s -> {s.setDeleted(1); s.setStatus(2);});
        this.updateBatchById(extSpus);

        // 设置查询分店信息的条件
        QueryWrapper<ExtSpu> q = new QueryWrapper<>();
        q.lambda().in(ExtSpu::getStoreId,storeIds).in(ExtSpu::getSpuId,baseSpuIds).eq(ExtSpu::getDeleted, 0);
        // 获取所有分店ExtSpu的id
        List<Long> brandExtSpuIds = this.getBaseMapper().selectList(q).stream().map(ExtSpu::getId).collect(Collectors.toList());
        // 删除分店的 ExtSpu
        ExtSpu update = new ExtSpu();
        update.setDeleted(1);
        update.setStatus(2);

        UpdateBatchParam<ExtSpu> updateBatchParam = new UpdateBatchParam();
        updateBatchParam.setWrapper(q);
        updateBatchParam.setUpdateEntity(update);
        this.updateBatchByWrapper(updateBatchParam);
        // 添加分店的 ExtSpu的Id
        allExtSpuId.addAll(brandExtSpuIds);
        this.delOtherMessage(allExtSpuId);
    }

    /**
     * 删除关联ExtSpu的其余的信息
     */
    private void delOtherMessage( List<Long> allExtSpuId) {

        // 删除营销类目
        QueryWrapper<SpuSalesCategory> qsc = new QueryWrapper<>();
        qsc.lambda().in(SpuSalesCategory::getExtSpuId, allExtSpuId).eq(SpuSalesCategory::getDeleted,0);
        SpuSalesCategory salesUpdate = new SpuSalesCategory();
        salesUpdate.setDeleted(1);

        UpdateBatchParam<SpuSalesCategory> updateSalesBatch = new UpdateBatchParam();
        updateSalesBatch.setWrapper(qsc);
        updateSalesBatch.setUpdateEntity(salesUpdate);
        spuSalesCategoryService.updateBatchByWrapper(updateSalesBatch);

        // 删除标签
        QueryWrapper<ExtSpuTags> tagWrapper = new QueryWrapper<>();
        tagWrapper.lambda().in(ExtSpuTags::getSpuId, allExtSpuId).eq(ExtSpuTags::getDeleted,0);
        ExtSpuTags tagsUpdate = new ExtSpuTags();
        tagsUpdate.setDeleted(1);

        UpdateBatchParam<ExtSpuTags> tagsBatch = new UpdateBatchParam();
        tagsBatch.setWrapper(tagWrapper);
        tagsBatch.setUpdateEntity(tagsUpdate);
        extSpuTagsService.updateBatchByWrapper(tagsBatch);

        // 设置商品图片资源表信息
        QueryWrapper<GoodsGallery> goodsGalleryQueryWrapper = new QueryWrapper<>();
        goodsGalleryQueryWrapper.lambda().in(GoodsGallery::getExtSpuId, allExtSpuId).eq(GoodsGallery::getDeleted,0);

        // 获得相册表的ID
        List<Long> galleryIdList = goodsGalleryService.getBaseMapper().selectList(goodsGalleryQueryWrapper)
                .stream().map(GoodsGallery::getGalleryId).collect(Collectors.toList());

        // 删除商品图片资源表
        GoodsGallery goodsGallery = new GoodsGallery();
        goodsGallery.setDeleted(1);

        UpdateBatchParam<GoodsGallery> goodsGalleryBatch = new UpdateBatchParam();
        goodsGalleryBatch.setWrapper(goodsGalleryQueryWrapper);
        goodsGalleryBatch.setUpdateEntity(goodsGallery);
        goodsGalleryService.updateBatchByWrapper(goodsGalleryBatch);


        // 删除相册信息
        QueryWrapper<Gallery> galleryWrapper = new QueryWrapper<>();
        galleryWrapper.lambda().in(Gallery::getId, galleryIdList).eq(Gallery::getDeleted,0);
        Gallery gallery = new Gallery();
        gallery.setDeleted(1);

        UpdateBatchParam<Gallery> galleryBatch = new UpdateBatchParam();
        galleryBatch.setWrapper(galleryWrapper);
        galleryBatch.setUpdateEntity(gallery);
        galleryService.updateBatchByWrapper(galleryBatch);
    }

    /**
     * 删除spu下的sku
     */
    private void delSkuUnderSpuById(List<Long> storeIds,Set<Long> baseSpuIds, Map<String, Object> map) {

        // 设置baseSku条件
        QueryWrapper<BaseSku> baseSkuWrapper = new QueryWrapper<>();
        baseSkuWrapper.lambda().in(BaseSku::getSpuId, baseSpuIds).eq(BaseSku::getCompanyId,map.get("companyId"))
                .eq(BaseSku::getDeleted, 0);
        // 获取需要删除的baseSku Id
        List<Long> baseSkuIds = baseSkuService.getBaseMapper().selectList(baseSkuWrapper)
                .stream().map(s -> s.getId()).distinct().collect(Collectors.toList());

        // 删除总店的BaseSku
        BaseSku updateBaseSku = new BaseSku();
        updateBaseSku.setDeleted(1);
        updateBaseSku.setStatus(2);

        UpdateBatchParam<BaseSku> baseSkuBatch = new UpdateBatchParam();
        baseSkuBatch.setWrapper(baseSkuWrapper);
        baseSkuBatch.setUpdateEntity(updateBaseSku);
        baseSkuService.updateBatchByWrapper(baseSkuBatch);


        // 查询需要删除的 ExtSku的Id: 作为ProductManage 删除的条件
        long parentStoreId = Long.parseLong(map.get("storeId") + "");
        storeIds.add(parentStoreId);
        QueryWrapper<ExtSku> extSkuBranchWrapper = new QueryWrapper<>();
        extSkuBranchWrapper.lambda().in(ExtSku::getSkuId, baseSkuIds).in(ExtSku::getStoreId, storeIds)
                .eq(ExtSku::getDeleted, 0);
        List<Long> storebranchExtSkuIds = extSkuService.getBaseMapper().selectList(extSkuBranchWrapper).stream()
                .map(s -> s.getId()).collect(Collectors.toList());

        // 删除分店信息
        List<OmnipotentWrapper> extSkuOmiList = new ArrayList<>();
        extSkuOmiList.add(OmnipotentWrapper.setWrapper("in","sku_id", baseSkuIds));
        extSkuOmiList.add(OmnipotentWrapper.setWrapper("in", "store_id", storeIds));
        extSkuOmiList.add(OmnipotentWrapper.setWrapper("eq", "deleted", 0));

        ExtSku updateBranchExtSku = new ExtSku();
        updateBranchExtSku.setDeleted(1);
        updateBranchExtSku.setStatus(3);

        OmnipotentParam<ExtSku> extSkuParam = new OmnipotentParam();
        extSkuParam.setWrappers(extSkuOmiList);
        extSkuParam.setEntity(updateBranchExtSku);
        extSkuService.omniExtSkuUpdate(extSkuParam);


        // 删除productManage 相关信息
        QueryWrapper<ProductManage> productMangeWrapper = new QueryWrapper<>();
        productMangeWrapper.lambda().in(ProductManage::getSkuId, storebranchExtSkuIds).eq(ProductManage::getDeleted, 0);
        ProductManage proManUpdate = new ProductManage();
        proManUpdate.setDeleted(1);

        UpdateBatchParam<ProductManage> productManageBatch = new UpdateBatchParam();
        productManageBatch.setWrapper(productMangeWrapper);
        productManageBatch.setUpdateEntity(proManUpdate);
        productManageService.updateBatchByWrapper(productManageBatch);

    }


    /**
     * 图片处理
     */
    private void imageHandle(List<ExtSpuDisplayVo> extSpuDisplayVos) {
        extSpuDisplayVos.forEach(baseSpuDisplayVo -> {
            String[] split = baseSpuDisplayVo.getSpuImage().split(",");
            List<String> images = Arrays.asList(split);
            baseSpuDisplayVo.setImageArr(images);
        });
    }

    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    @Logable(authName = "根据自定义条件批量更新")
    @Override
    public boolean updateBatchByWrapper(UpdateBatchParam<ExtSpu> updateBatchParam) {
        ExtSpu updateEntity = updateBatchParam.getUpdateEntity();
        QueryWrapper<ExtSpu> wrapper = updateBatchParam.getWrapper();
        return this.update(updateEntity, wrapper);
    }

    @Override
    public List<ExtSpu> omnipotentQuery(List<OmnipotentWrapper> wrappers) {
        OmnipotentWrapper<ExtSpu> omnipotentWrapper = new OmnipotentWrapper<>();
        QueryWrapper<ExtSpu> wrapper = omnipotentWrapper.getWrapper(wrappers);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<ExtSpu> getSimilarExtSpuById(Long id) {
        return extSpuMapper.getSimilarExtSpuById(id);
    }

    /**
     * 获取最大权重值
     */
    @Override
    public Long getMaxWeight(Long storeId) {
        return extSpuMapper.getMaxWeight(storeId);
    }

    /**
     * 权重更新
     */
    @CacheEvict(cacheNames = "ExtSpu", allEntries = true)
    @Logable(authName = "权重更新")
    @Override
    public Boolean updateWeight(Map<String, Object> weightMap) {
        long extSpuId = Long.parseLong(weightMap.get("id").toString());
        long weight = Long.parseLong(weightMap.get("weight").toString());
        long storeId = Long.parseLong(weightMap.get("storeId").toString());
        // 查询该权重在数据库中是否已经存在
        QueryWrapper<ExtSpu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExtSpu::getWeight, weight).eq(ExtSpu::getStoreId, storeId).eq(ExtSpu::getDeleted, 0);

        List<ExtSpu> extSpus = baseMapper.selectList(wrapper);
        if (!extSpus.isEmpty()) {
            throw new ServiceException("该权重已经存在, 不能修改为该权重");
        }

        ExtSpu update = new ExtSpu();
        update.setId(extSpuId);
        update.setWeight(weight);
        this.updateById(update);
        return true;
    }


    private List<Long> storeIds(Long mainStoreId) {
        PlatStoreQueryParam param = new PlatStoreQueryParam();
        param.setPageNumber("1");
        param.setPageSize("10000");
        param.setParentId(mainStoreId);
        Response<Page<PlatStore>> listPlatStore = storeFeignService.getPlatStorePage(param);
        List<Long> listBranchStoreIds = listPlatStore.getData().getRecords().stream().map(PlatStore::getId).collect(Collectors.toList());
        listBranchStoreIds.add(mainStoreId);
        return listBranchStoreIds;
    }

    /**
     * 批量删除供应商sku
     */
    private void deletedVendorGoodsSku(Set<Long> baseSpuIds) {
        OmnipotentParam<VendorGoodsSku> omni = new OmnipotentParam<>();
        List<OmnipotentWrapper> vendorGoodsSkus = new ArrayList<>();
        vendorGoodsSkus.add(OmnipotentWrapper.setWrapper("in", "spu_id", baseSpuIds));
        vendorGoodsSkus.add(OmnipotentWrapper.setWrapper("eq", "deleted", 0));

        VendorGoodsSku entity = new VendorGoodsSku();
        entity.setDeleted(1);

        omni.setWrappers(vendorGoodsSkus);
        omni.setEntity(entity);
        vendorGoodsSkuService.updateBatch(omni);
    }

    /**
     * 批量删除baseGoodsGallery
     */
    private void deletedBaseGoodsGallery(Set<Long> baseSpuIds) {
        OmnipotentParam<BaseGoodsGallery> omni = new OmnipotentParam<>();
        List<OmnipotentWrapper> wrappers = new ArrayList<>();
        wrappers.add(OmnipotentWrapper.setWrapper("in", "goods_id", baseSpuIds));
        wrappers.add(OmnipotentWrapper.setWrapper("eq", "deleted", 0));

        BaseGoodsGallery entity = new BaseGoodsGallery();
        entity.setDeleted(1);

        omni.setWrappers(wrappers);
        omni.setEntity(entity);
        baseGoodsGalleryService.updateBatch(omni);
    }

    /**
     * 通用的更新操作
     */
    @Override
    public boolean updateBatch(OmnipotentParam<ExtSpu> param) {
        OmnipotentWrapper<ExtSku> omiWrapper = new OmnipotentWrapper<>();
        UpdateWrapper updateWrapper = omiWrapper.getUpdateWrapper(param.getWrappers());
        ExtSpu entityUpdate = param.getEntity();
        return this.update(entityUpdate, updateWrapper);
    }

}